package com.spic.business.manual.policy;

import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.policy.DynamicTableRenderPolicy;
import com.deepoove.poi.policy.TableRenderPolicy;
import com.deepoove.poi.util.TableTools;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * SchedulePolicy
 *
 * @author xuxiaochang@chinasofi.com
 * @date 2022/6/17
 */
public class SchedulePolicy extends DynamicTableRenderPolicy
{
    @Override
    public void render(XWPFTable xwpfTable, Object data) throws Exception
    {
        int begin = 1;
        if (null == data) {return;}
        List<RowRenderData> scheduleData = (List<RowRenderData>) data;
        LinkedHashMap<String, List<RowRenderData>> collect = scheduleData.stream().collect(Collectors.groupingBy(item -> item.getCells().get(0).toString(), LinkedHashMap::new, Collectors.toList()));
        Set<Map.Entry<String, List<RowRenderData>>> entries = collect.entrySet();
        int[] days = new int[entries.size()];
        int num = 0;
        Iterator<Map.Entry<String, List<RowRenderData>>> iterator = entries.iterator();
        while (iterator.hasNext())
        {
            List<RowRenderData> value = iterator.next().getValue();
            days[num] = value == null ? 0 : value.size();
            num++;
        }
        //先删除第一行
        xwpfTable.removeRow(begin);
        for (int i = 0; i < scheduleData.size(); i++)
        {
            XWPFTableRow insertNewTableRow = xwpfTable.insertNewTableRow(begin);
            for (int j = 0; j < 5; j++)
            {
                insertNewTableRow.createCell();
            }
            // 单行渲染
            TableRenderPolicy.Helper.renderRow(xwpfTable.getRow(begin), scheduleData.get(i));
        }
            int fromRow = begin;
            int toRow = 0;
            // 合并单元格
            for (int j = 0; j < days.length; j++)
            {
                toRow += days[j];
                if (fromRow < toRow)
                {
                    TableTools.mergeCellsVertically(xwpfTable, 0, fromRow, toRow);
                }
                fromRow = toRow + 1;
            }
    }
}
